﻿namespace EFS.RC.Common
{
	public static class Utilities
	{
		/// <summary>
		/// Compares if 2 Sip Uri's
		/// </summary>
		/// <param name="sipUri1">Sip Uri1</param>
		/// <param name="sipUri2">Sip Uri2</param>
		/// <returns>True if 2 sipUris are equal. False otherwise.</returns>
		public static System.Boolean SipUriCompare(string sipUri1, string sipUri2)
		{
			// check
			EFS.Common.Verify.String(sipUri1, "sipUri1");
			EFS.Common.Verify.String(sipUri2, "sipUri2");

			// not equal
			System.Boolean areEqual = false;

			// check string equal
			if (System.String.Equals(sipUri1, sipUri2, System.StringComparison.OrdinalIgnoreCase))
			{
				areEqual = true;
			}
			else
			{
				// rta	
				Microsoft.Rtc.Signaling.RealTimeAddress address1 = new Microsoft.Rtc.Signaling.RealTimeAddress(sipUri1);
				Microsoft.Rtc.Signaling.RealTimeAddress address2 = new Microsoft.Rtc.Signaling.RealTimeAddress(sipUri2);

				// check
				areEqual = (address1 == address2);
			}

			// done
			return areEqual;
		}

		/// <summary>
		/// Cleanup Sip / Uri
		/// </summary>
		/// <param name="sipUri1">Sip Uri1</param>
		/// <returns>True if 2 sipUris are equal. False otherwise.</returns>
		public static System.String SipUriCleanup(string sipUri)
		{
			// check
			EFS.Common.Verify.String(sipUri, "sipUri");

			// remove domain
			System.Int32 indexOfAt = sipUri.IndexOf("@");
			if (indexOfAt >= 0)
			{
				sipUri = sipUri.Remove(indexOfAt);
			}

			// remove domain
			System.Int32 indexOfSemicolon = sipUri.IndexOf(";");
			if (indexOfSemicolon >= 0)
			{
				sipUri = sipUri.Remove(indexOfSemicolon);
			}

			// clean
			sipUri = sipUri.Replace("tel:+", "");
			sipUri = sipUri.Replace("sip:+", "");
			sipUri = sipUri.Replace("tel:", "");
			sipUri = sipUri.Replace("sip:", "");

			// done
			return sipUri;
		}

		/// <summary>
		/// Normalize
		/// </summary>
		/// <param name="uri"></param>
		/// <returns></returns>
		public static System.String UserUri(System.String uri, System.String domain)
		{
			// real time address
			Microsoft.Rtc.Signaling.RealTimeAddress realTimeAddress = new Microsoft.Rtc.Signaling.RealTimeAddress(uri);

			// clean
			System.String cleanUri = SipUriCleanup(uri);

			// log
			EFS.EventLog.Log.LogInfo(System.String.Format("EFS.RC.Common..Utilities.UserUri {0} clean {1}", uri, cleanUri));

			// check
			if (realTimeAddress.IsPhone)
			{
				EFS.EventLog.Log.LogInfo(System.String.Format("EFS.RC.Common..Utilities.UserUri {0} Is Phone; Length is {1}", uri, cleanUri.Length));

				// check length
				if (4 == cleanUri.Length)
				{
					// extension
					return System.String.Format("ext={0}", cleanUri);
				}

				// normal tell
				return System.String.Format("tel:+{0}", cleanUri);
			}

			// sip
			return System.String.Format("sip:{0}@{1}", cleanUri, domain);
		}
	}
}
